package com.sunseaypw.springmvc.web.api;

import java.util.Map;

import com.sunseaypw.springmvc.entity.User;
import com.sunseaypw.springmvc.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//编写REST接口只需要定义@RestController，然后，每个方法都是一个API接口，
//  输入和输出只要能被Jackson序列化或反序列化为JSON就没有问题。
@RestController
@RequestMapping("/api2")
public class Cont2 {
    @Autowired
    UserService userService;

    @GetMapping("/users/{id}")
    public User user(@PathVariable("id") long id) {
        return userService.getUserById(id);
    }

    @PostMapping("/signin")
    public Map<String, Object> signin(@RequestBody SignInRequest signinRequest) {
        try {
            User user = userService.signin(signinRequest.email, signinRequest.password);
            return Map.of("user", user);
        } catch (Exception e) {
            return Map.of("error", "SIGNIN_FAILED", "message", e.getMessage());
        }
    }

    public static class SignInRequest {
        public String email;
        public String password;
    }
}